package cn.chencq.moudle.job.task;

import java.io.IOException;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

import cn.chencq.moudle.thuser.entity.ThUser;
import cn.chencq.moudle.thuser.service.ThUserService;
import cn.chencq.utils.DateUtils;
import cn.chencq.utils.RandomUtils;
import cn.chencq.utils.ThRequestUtils;

@Component("spiderThInfoTask")
public class SpiderThInfoTask {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private ThUserService thUserService;

	public void spider(String param) {
		JSONObject json = JSONObject.parseObject(param);
		String opt = json.getString("opt"); // 3
		int start = json.getIntValue("start");
		int end = json.getIntValue("end");
		for (int uid = start; uid < end; uid++) {
			JSONObject auth = new JSONObject();
			auth.put("loginType", "1");
			auth.put("imei", "1");
			auth.put("time_stamp", DateUtils.date2Str(new Date(), "yyyyMMddhhmmsssss"));
			auth.put("UID", uid);

			String res = "";
			try {
				res = ThRequestUtils.thRequest(opt, auth.toString(), null);
			} catch (IOException e) {
				logger.info("天宏用户数据异常", e);
			}

			logger.info("天宏用户数据, res:{}", res);
			JSONObject s = JSONObject.parseObject(res);
			if (null != s && "0".equals(s.getString("error"))) {
				ThUser user = JSONObject.parseObject(res, ThUser.class);
				getBankCardInfo(user, auth);
				thUserService.saveOrUpdate(user);
			}
		}

	}

	private ThUser getBankCardInfo(ThUser user, JSONObject auth) {
		try {
			String res = ThRequestUtils.thRequest("109", auth.toString(), null);
			JSONObject s = JSONObject.parseObject(res);
			if (null != s && "0".equals(s.getString("error"))) {
				JSONObject card = s.getJSONArray("cards").getJSONObject(0);
				user.setBankCardId(card.getString("ID"));
				user.setBankCardNumber(card.getString("BankCardNumber"));
				user.setBankTypeName(card.getString("BankTypeName"));
				user.setBankUserName(card.getString("BankUserName"));
			}
		} catch (Exception e) {
			logger.error("获取用户绑定银行卡信息失败", e);
		}
		return user;
	}

	public void checkLoginPassword(String param) {
		// 登录密码最长12位
		String password = RandomUtils.getLoginPassword();
		thUserService.checkLoginPassword(null, password, param);
	}

	public void checkWithdrawPassword(String param) {
		String password = RandomUtils.getWithdrawPassword();
		thUserService.checkWithdrawPassword(password, param);
	}
}
